﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class UserControl_ControlNhapHoaDonBanHang : System.Web.UI.UserControl
{
    private string SCRIPT_DOFOCUS = webapp4U.UI.Forcus.SCRIPT_DOFOCUS;
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    double priceTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            webapp4U.UI.Forcus.HookOnFocus(this.Page as Control);                
            if (ViewState["flag"] == null)
            {
                ViewState["flag"] = false;
                GridProductEmpty();
            }
            DataBind();
           
        }
        if (ViewState["strSoHoaDon"] != null)
        {
            ControlReportViewer1.ReportViewer.Report = CreateReport(ViewState["strSoHoaDon"].ToString());            
        }
        GridProductEmptyColumnSpan();
        ScriptManager.RegisterStartupScript(this, typeof(UserControl_ControlNhapHoaDonBanHang), "ScriptDoFocus", SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", Request["__LASTFOCUS"]), true);
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    void GridProductEmptyColumnSpan()
    {
        if (grvListOrderDetail.Rows.Count > 0)
        {
            if (grvListOrderDetail.Rows[0].Cells[0].Text == "Thêm mặt hàng")
            {
                int TotalColumns = grvListOrderDetail.Rows[0].Cells.Count;
                grvListOrderDetail.Rows[0].Cells.Clear();
                grvListOrderDetail.Rows[0].Cells.Add(new TableCell());
                grvListOrderDetail.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                grvListOrderDetail.Rows[0].Cells[0].Text = "Thêm mặt hàng";
            }
        }
    }
    void GridProductEmpty()
    {
        DataTable table = new DataTable();
        DataColumn col1 = new DataColumn("Mã hàng");
        DataColumn col2 = new DataColumn("Tên hàng");
        DataColumn col3 = new DataColumn("Đơn giá");
        DataColumn col4 = new DataColumn("Số lượng");
        DataColumn col5 = new DataColumn("Chiết khấu");
        DataColumn col6 = new DataColumn("Thành tiền");
       

        col1.DataType = System.Type.GetType("System.String");
        col2.DataType = System.Type.GetType("System.String");
        col3.DataType = System.Type.GetType("System.Double");
        col4.DataType = System.Type.GetType("System.Double");
        col5.DataType = System.Type.GetType("System.Double");
        col6.DataType = System.Type.GetType("System.Double");
     

        table.Columns.Add(col1);
        table.Columns.Add(col2);
        table.Columns.Add(col3);
        table.Columns.Add(col4);
        table.Columns.Add(col5);
        table.Columns.Add(col6);
        
        //Create a Row in the DataTable table
        DataRow row = table.NewRow();
        //Fill All Columns with Data
        row[col1] = "";
        row[col2] = "";
        row[col3] = 0;
        //row[col4] = 0;
        //row[col5] = 0;
        row[col6] = 0;
        
        table.Rows.Add(row);

        grvListOrderDetail.DataSource = table;
        grvListOrderDetail.DataBind();

        //Gop column
        int TotalColumns = grvListOrderDetail.Rows[0].Cells.Count;
        grvListOrderDetail.Rows[0].Cells.Clear();
        grvListOrderDetail.Rows[0].Cells.Add(new TableCell());
        grvListOrderDetail.Rows[0].Cells[0].ColumnSpan = TotalColumns;
        grvListOrderDetail.Rows[0].Cells[0].Text = "Thêm mặt hàng";
        grvListOrderDetail.DataBind();
    }
    void UpdateGridProduct()
    {
        //grvListOrderDetail
        TextBox txtMaHang = grvListOrderDetail.FooterRow.FindControl("txtMaHang") as TextBox;
        TextBox txtTenHang = grvListOrderDetail.FooterRow.FindControl("txtTenHang") as TextBox;
        TextBox txtSoLuong = grvListOrderDetail.FooterRow.FindControl("txtSoLuong") as TextBox;
        TextBox txtPrice = grvListOrderDetail.FooterRow.FindControl("txtPrice") as TextBox;
        
        DataTable table = new DataTable();
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == txtMaHang.Text)
                {
                    dr[3] = Double.Parse(dr[3].ToString()) + Double.Parse(txtSoLuong.Text);
                    dr[5] = Double.Parse(dr[3].ToString()) * Double.Parse(dr[2].ToString()) * (100 - Double.Parse(dr[4].ToString())) / 100;
                    ViewState["KhoHangTemp"] = table;
                    grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
                    grvListOrderDetail.DataBind();
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data

            row[0] = txtMaHang.Text;
            row[1] = txtTenHang.Text;
            row[2] = Double.Parse(txtPrice.Text);
            row[3] = Double.Parse(txtSoLuong.Text);
            row[4] = 0;
            row[5] = Double.Parse(txtSoLuong.Text) * Double.Parse(txtPrice.Text);// *(100 - 0) / 100;
           
            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("Mã hàng");
            DataColumn col2 = new DataColumn("Tên hàng");
            DataColumn col3 = new DataColumn("Đơn giá");
            DataColumn col4 = new DataColumn("Số lượng");
            DataColumn col5 = new DataColumn("Chiết khấu");
            DataColumn col6 = new DataColumn("Thành tiền");
           

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.Double");
            col4.DataType = System.Type.GetType("System.Double");
            col5.DataType = System.Type.GetType("System.Double");
            col6.DataType = System.Type.GetType("System.Double");
         

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            table.Columns.Add(col4);
            table.Columns.Add(col5);
            table.Columns.Add(col6);
            
            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = txtMaHang.Text;
            row[col2] = txtTenHang.Text;
            row[col3] = Double.Parse(txtPrice.Text);
            row[col4] = Double.Parse(txtSoLuong.Text);
            row[col5] = 0;
            row[col6] = Double.Parse(txtSoLuong.Text) * Double.Parse(txtPrice.Text); //* (100 - 0) / 100;
            
            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }
        grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
        grvListOrderDetail.DataBind();

        txtMaHang.Text = "";
        txtTenHang.Text = "";
        txtPrice.Text = "";
        txtSoLuong.Text = "";
        txtMaHang.Focus();
    }
    protected void btAdd_Click(object sender, EventArgs e)
    {
        if ((bool)ViewState["flag"])
        {
            UpdateGridProduct();
        }
        else
        {
            ShowMessageBox("Phải nhấn nút tạo mới");
        }        
    }
    protected void txtSoLuong_TextChanged(object sender, EventArgs e)
    {
        if ((bool)ViewState["flag"])
        {
            UpdateGridProduct();
        }
        else
        {
            ShowMessageBox("Phải nhấn nút tạo mới");
        }
    }
    void UpdateGridKM()
    {
        DataTable table = new DataTable();
        if (ViewState["KhoHangTempKM"] != null)
        {
            table = (DataTable)ViewState["KhoHangTempKM"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() ==txtMaHangKM.Text)
                {
                    dr[2] = Double.Parse(dr[2].ToString()) + 1;
                 
                    ViewState["KhoHangTempKM"] = table;
                    grvKM.DataSource = ViewState["KhoHangTempKM"];
                    grvKM.DataBind();
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data

            row[0] = txtMaHangKM.Text;
            row[1] = txtTenHangKM.Text;
           
            row[2] = 1;
           

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("Mã hàng");
            DataColumn col2 = new DataColumn("Tên hàng");
            DataColumn col3 = new DataColumn("Số lượng");
          


            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.Double");
           


            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
          

            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] =txtMaHangKM.Text;
            row[col2] =txtTenHangKM.Text;
            row[col3] = 1;
           

            table.Rows.Add(row);

            ViewState["KhoHangTempKM"] = table;
        }
        grvKM.DataSource = ViewState["KhoHangTempKM"];
        grvKM.DataBind();
    }
    protected void btAddKM_Click(object sender, EventArgs e)
    {
        UpdateGridKM();
        txtMaHangKM.Text = "";
        txtTenHangKM.Text = "";
        txtMaHangKM.Focus();
    }
    protected void grvKM_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvKM.EditIndex = -1;
        grvKM.DataSource = ViewState["KhoHangTempKM"];
        grvKM.DataBind();
    }
    protected void grvKM_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvKM.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTempKM"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTempKM"] = table;

                grvKM.EditIndex = -1;
                grvKM.DataSource = ViewState["KhoHangTempKM"];
                grvKM.DataBind();
                return;
            }
            i++;
        }
    }
    protected void grvKM_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvKM.EditIndex = e.NewEditIndex;
        grvKM.DataSource = ViewState["KhoHangTempKM"];
        grvKM.DataBind();
    }
    protected void grvKM_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvKM.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtSL = (TextBox)grvKM.Rows[e.RowIndex].FindControl("txtSL");

            if ((txtSL.Text == "") || (txtSL.Text == "0"))
            {
                txtSL.Text = "1";
            }
            Double SL = Double.Parse(txtSL.Text);
            
            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTempKM"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[2] = SL;
                    table.AcceptChanges();
                    ViewState["KhoHangTempKM"] = table;

                    grvKM.EditIndex = -1;
                    grvKM.DataSource = ViewState["KhoHangTempKM"];
                    grvKM.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvListOrderDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvListOrderDetail.EditIndex = -1;
        grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
        grvListOrderDetail.DataBind();
    }
    protected void grvListOrderDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvListOrderDetail.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvListOrderDetail.EditIndex = -1;
                grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
                grvListOrderDetail.DataBind();
                return;
            }
            i++;
        }
    }
    protected void grvListOrderDetail_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvListOrderDetail.EditIndex = e.NewEditIndex;
        grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
        grvListOrderDetail.DataBind();
    }
    protected void grvListOrderDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvListOrderDetail.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtSL = (TextBox)grvListOrderDetail.Rows[e.RowIndex].FindControl("txtSL");
            TextBox txtChietKhauGrid = (TextBox)grvListOrderDetail.Rows[e.RowIndex].FindControl("txtCK");

            if ((txtSL.Text == "") || (txtSL.Text == "0"))
            {
                txtSL.Text = "1";
            }
            if (txtChietKhauGrid.Text == "")
            {
                txtChietKhauGrid.Text = "0";
            }

            Double SL = Double.Parse(txtSL.Text);
            Double CK = Double.Parse(txtChietKhauGrid.Text);

            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[3] = SL;
                    dr[4] = CK;
                    dr[5] = SL * Double.Parse(dr[2].ToString()) * (100 - CK) / 100;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvListOrderDetail.EditIndex = -1;
                    grvListOrderDetail.DataSource = ViewState["KhoHangTemp"];
                    grvListOrderDetail.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvListOrderDetail_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            priceTotal += double.Parse(DataBinder.Eval(e.Row.DataItem, "Thành tiền").ToString());
            txtTongTien.Text = string.Format("{0:#,#}", priceTotal);

        }
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        GridProductEmpty();

        if ( ViewState["KhoHangTempKM"]!=null)
        {
            ViewState["KhoHangTempKM"] = null;
        }
        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;
        }
        if(ViewState["strSoHoaDon"] !=null)
        {
            if (ViewState["dsChiTietHoaDon"] != null)
            {
                ViewState["dsChiTietHoaDon"] = null;
            }
            ViewState["strSoHoaDon"] = null;
        }

        txtMaKhachHang.Text = "";
        txtDate.Text = Session["workingday"].ToString(); 
        txtTenKhachHang.Text = "";

        TextBox txtMaHang = grvListOrderDetail.FooterRow.FindControl("txtMaHang") as TextBox;
        TextBox txtTenHang = grvListOrderDetail.FooterRow.FindControl("txtTenHang") as TextBox;
        TextBox txtSoLuong = grvListOrderDetail.FooterRow.FindControl("txtSoLuong") as TextBox;
        TextBox txtPrice = grvListOrderDetail.FooterRow.FindControl("txtPrice") as TextBox;

        txtMaHang.Text = "";
        txtTenHang.Text = "";
        txtPrice.Text = "";
        txtSoLuong.Text = "1";
        txtMaKhachHang.Focus();
        ViewState["flag"] = true;
        TabContainer1.ActiveTabIndex = 0;
        
    }
    public int CompareDate(string sdate1, string sdate2)
    {
        try
        {
            DateTime date1 = new DateTime(int.Parse(sdate1.Substring(6, 4)), int.Parse(sdate1.Substring(3, 2)), int.Parse(sdate1.Substring(0, 2)));
            DateTime date2 = new DateTime(int.Parse(sdate2.Substring(6, 4)), int.Parse(sdate2.Substring(3, 2)), int.Parse(sdate2.Substring(0, 2)));
            int result = DateTime.Compare(date1, date2);
            return result;
        }
        catch { return -1; }
        //if (result < 0)
        //    relationship = "sdate1 is earlier than";
        //else if (result == 0)
        //    relationship = "is the same time as";
        //else
        //    relationship = "sdate 1 is later than";

    }
    protected void btSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string tranno = "";
            if ((bool)ViewState["flag"])
            {
                
                double dTienPhaiTra = 0;
                double dTienHoaDon = Double.Parse(lblSoTien.Text);
                double dTienGiam = 0;
                dTienGiam = Double.Parse(txtSoTienGiam.Text);

                dTienPhaiTra = dTienHoaDon - dTienGiam;

                lblSoTienPhaiTra.Text = dTienPhaiTra.ToString();


                tranno = dt.GetDataDepend(str, "[k_getDocNoGetOrderDaily]", CommandType.StoredProcedure, ref error,
                         new SqlParameter("@sitecode", Session["sitecode"].ToString()));



                dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_InserArhdr", ref error,
                       new SqlParameter("@Tranno", tranno),
                       new SqlParameter("@dotdate",txtDate.Text),
                       new SqlParameter("@doctot", float.Parse(txtTongTien.Text)),
                       new SqlParameter("@Recuser", Session["user"].ToString()),
                       new SqlParameter("@customer_key", int.Parse(txtMaKhachHang.Text)),
                       new SqlParameter("@realdoctot", lblSoTienPhaiTra.Text));
                int i = 1;
                bool kqSaveHDNotKM = false;
                foreach (GridViewRow grv in grvListOrderDetail.Rows)
                {
                    Label lblMaHangGrid = (Label)grv.FindControl("lblMaHang");
                    Label lblTenHangGrid = (Label)grv.FindControl("lblTenHang");
                    Label lblSLGrid = (Label)grv.FindControl("lblSL");
                    Label lblDGGrid = (Label)grv.FindControl("lblDG");
                    Label lblCKGrid = (Label)grv.FindControl("lblCK");
                    Label lblTenHang = (Label)grv.FindControl("lblTenHang");
                    Label lblThanhTien = (Label)grv.FindControl("lblThanhTien");

                    kqSaveHDNotKM = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "[ls_saveInvoiceDetail]", ref error,
                        new SqlParameter("@tranNo", tranno),
                        new SqlParameter("@itemKey", lblMaHangGrid.Text),
                        new SqlParameter("@toDay",txtDate.Text),
                        new SqlParameter("@itemDesc", lblTenHangGrid.Text),
                        new SqlParameter("@price", float.Parse(lblDGGrid.Text)),
                        new SqlParameter("@qty", float.Parse(lblSLGrid.Text)),
                        new SqlParameter("@Disc", float.Parse(lblCKGrid.Text)),
                        new SqlParameter("@siteCode", Session["sitecode"].ToString()),
                        new SqlParameter("@rowNum", i),
                        new SqlParameter("@lineType", "0"));
                    i++;
                }
                bool kqSaveHDHaveKM = false;
                if (grvKM.Rows.Count > 0)
                {
                    foreach (GridViewRow grv in grvKM.Rows)
                    {
                        Label lblMaHangGridKM = (Label)grv.FindControl("lblMaHang");
                        Label lblTenHangGridKM = (Label)grv.FindControl("lblTenHang");
                        Label lblSLGridKM = (Label)grv.FindControl("lblSL");
                        kqSaveHDHaveKM = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "[ls_saveInvoiceDetail]", ref error,
                          new SqlParameter("@tranNo", tranno),
                          new SqlParameter("@itemKey", lblMaHangGridKM.Text),
                          new SqlParameter("@toDay", txtDate.Text),
                          new SqlParameter("@itemDesc", lblTenHangGridKM.Text),
                          new SqlParameter("@price", float.Parse("0")),
                          new SqlParameter("@qty", float.Parse(lblSLGridKM.Text)),
                          new SqlParameter("@Disc", float.Parse("0")),
                          new SqlParameter("@siteCode", Session["sitecode"].ToString()),
                          new SqlParameter("@rowNum", i),
                          new SqlParameter("@lineType", "KM"));
                        i++;
                    }
                }
                if (kqSaveHDNotKM)
                {
                    ASPxPopupControl1.ShowOnPageLoad = false;

                    //ShowMessageBox("Đơn hàng lưu thành công");

                    ViewState["strSoHoaDon"] = tranno;
                    TabContainer1.ActiveTabIndex = 1;
                   
                    ControlReportViewer1.ReportViewer.Report = CreateReport(tranno);
                    DataBind();
                    
                    txtMaKhachHang.Text = "";
                    txtTenKhachHang.Text = "";

                    //
                    TextBox txtMaHang = grvListOrderDetail.FooterRow.FindControl("txtMaHang") as TextBox;
                    TextBox txtTenHang = grvListOrderDetail.FooterRow.FindControl("txtTenHang") as TextBox;
                    TextBox txtSoLuong = grvListOrderDetail.FooterRow.FindControl("txtSoLuong") as TextBox;
                    TextBox txtPrice = grvListOrderDetail.FooterRow.FindControl("txtPrice") as TextBox;

                    txtMaHang.Text = "";
                    txtTenHang.Text = "";
                    txtPrice.Text = "";
                    txtSoLuong.Text = "";
                    txtTongTien.Text = "";

                    txtSoTienGiam.Text = "0";
                    
                    ViewState["flag"] = false;

                }
                else
                {
                    ShowMessageBox(error);
                }

            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }    
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
          int checkkhoaso = CompareDate(txtDate.Text, Session["workingday"].ToString());
          if (checkkhoaso < 0)
          {
              ShowMessageBox("Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString());
              txtDate.Focus();
          }
          else
          {
              ASPxPopupControl1.HeaderText = "Xác nhận số tiền đơn hàng";
              ASPxPopupControl1.Left = 400;
              ASPxPopupControl1.Top = 600;
              //ASPxPopupControl1.Text = "Xác nhận số tiền hóa đơn";
              ASPxPopupControl1.ShowOnPageLoad = true;
              lblSoTien.Text = txtTongTien.Text;
              lblSoTienPhaiTra.Text = lblSoTien.Text;
          }
    }
    
    protected void txtMaKhachHang_TextChanged(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        GridProductEmptyColumnSpan();
        try
        {
            TextBox txtMaHang = grvListOrderDetail.FooterRow.FindControl("txtMaHang") as TextBox;
            
            string Chuoi = txtMaKhachHang.Text;
            int index = Chuoi.IndexOf("|");
            txtMaKhachHang.Text = Chuoi.Substring(0, index - 1);
            txtTenKhachHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);
            txtMaHang.Focus();
            
            //txtOldPrice.Text = dt.GetDataDepend(str, "k_getPice", CommandType.StoredProcedure, ref error,
              //  new SqlParameter("@itemkey", txtMaHang.Text));
            //txtNewPrice.Focus();

        }
        catch
        {
            return;
        }
    }
    protected void txtMaHang_TextChanged(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        GridProductEmptyColumnSpan();
        try
        {
            TextBox txtMaHang = grvListOrderDetail.FooterRow.FindControl("txtMaHang") as TextBox;
            TextBox txtTenHang = grvListOrderDetail.FooterRow.FindControl("txtTenHang") as TextBox;
            TextBox txtSoLuong = grvListOrderDetail.FooterRow.FindControl("txtSoLuong") as TextBox;
            TextBox txtPrice = grvListOrderDetail.FooterRow.FindControl("txtPrice") as TextBox;

            string Chuoi = txtMaHang.Text;
            int index = Chuoi.IndexOf("|");
            txtMaHang.Text = Chuoi.Substring(0, index - 1);
            txtTenHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);

            txtPrice.Text = dt.GetDataDepend(str, "k_getPice", CommandType.StoredProcedure, ref error,
                new SqlParameter("@itemkey", txtMaHang.Text),
                new SqlParameter("@sitecode",Session["sitecode"].ToString()));

            txtSoLuong.Focus();

        }
        catch
        {
            return;
        }
    }
    protected void txtMaHangKM_TextChanged(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        GridProductEmptyColumnSpan();
        try
        {
            string Chuoi = txtMaHangKM.Text;
            int index = Chuoi.IndexOf("|");
            txtMaHangKM.Text = Chuoi.Substring(0, index - 1);
            txtTenHangKM.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);     

        }
        catch
        {
            return;
        }
    }
  
   
    DevExpress.XtraReports.UI.XtraReport CreateReport(string tranno)
    {
        XtraReportInHoaDonBanHang tableReport = new XtraReportInHoaDonBanHang();
        if (Session["Sitecode"] != null)
        {
           
           
            dt = new ClassExecute.ClassExecute();
            DataSet ds = new DataSet();

            string strTenCuaHang, strDiaChiCuaHang, strDTCuaHang;
            strDiaChiCuaHang = "";
            strDTCuaHang = "";
            strTenCuaHang = "";
            DataTable dtCuaHang = dt.Get_Data_DataTable(str, ref error, "TTr_getCuaHang_Branchlist", CommandType.StoredProcedure, new SqlParameter("@Sitecode", Session["Sitecode"].ToString()));
            if (dtCuaHang.Rows.Count > 0)
            {
                strTenCuaHang = dtCuaHang.Rows[0]["sitename"].ToString();
                strDiaChiCuaHang = dtCuaHang.Rows[0]["Address"].ToString();
                strDTCuaHang = dtCuaHang.Rows[0]["Tel"].ToString();
            }

            if (ViewState["dsChiTietHoaDon"] == null)
            {

                ds = dt.Get_Data_DataSet(str, ref error, "TTr_getChiTietHoaDon_Arlin", CommandType.StoredProcedure,
                    new SqlParameter("@Sitecode", Session["Sitecode"].ToString()),
                    new SqlParameter("@tranno", tranno));
                ViewState["dsChiTietHoaDon"] = ds;
            }
            else
            {
                ds = (DataSet)ViewState["dsChiTietHoaDon"];
            }
            //xác minh đơn hàng
            dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "ls_closeInvoice", ref error,
                new SqlParameter("@tranno", tranno),
                new SqlParameter("@siteCode", Session["sitecode"].ToString()));

            
            tableReport.SetReportParameter(ds, strTenCuaHang, strDiaChiCuaHang, strDTCuaHang);
            
        }
        return tableReport;
    }

    protected void txtSoTienGiam_TextChanged(object sender, EventArgs e)
    {
        GridProductEmptyColumnSpan();
        double dTienPhaiTra = 0;
        double dTienHoaDon = Double.Parse(lblSoTien.Text);
        double dTienGiam = 0;
        dTienGiam = Double.Parse(txtSoTienGiam.Text);

        dTienPhaiTra = dTienHoaDon - dTienGiam;

        lblSoTienPhaiTra.Text = string.Format("{0:#,#}", dTienPhaiTra); 
    }
}